package cn.hinglo.wx.kit;

import cn.hinglo.wx.entity.WeixinUserInfo;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/***
 * 微信网页授权登录
 * @author hinglo
 * @date 2019/05/31
 */
@Slf4j
public class WebAuthKit {

    private static final String APP_ID = PropKit.use("application.properties").get("appId");

    private static final String SECRET = PropKit.use("application.properties").get("secret");


    /***
     * 微信网页授权信息获取
     * @param code 换取码code
     * @return 返回用户信息
     */
    public static WeixinUserInfo getWebAuthUserInfo(String code) {
        if (StrKit.isBlank(code)) {
            log.info("获取用户信息失败,换取码code不能为空");
            return null;
        }
        JSON dataToken = getToken(code);
        if (dataToken == null || dataToken.getByPath("errcode") != null) {
            log.info("获取用户信息失败,未通过code获取到accessToken与openId,错误码：{}", dataToken != null ? dataToken.getByPath("errcode") : "无");
            return null;
        }
        String token = (String) dataToken.getByPath("access_token");
        String openId = (String) dataToken.getByPath("openid");
        JSON userInfo = getUserInfo(token, openId);
        if (userInfo == null || userInfo.getByPath("errcode") != null) {
            log.info("未通过accessToken与openID获取到用户信息,错误码：{}", userInfo != null ? userInfo.getByPath("errcode") : "无");
            return null;
        }
        return data(userInfo);
    }


    /***
     * 通过code 换取accessToken
     * @param code code
     * @return 返回结果
     */
    private static JSON getToken(String code) {
        // 通过code换token
        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s&secret=%s&code=%s&grant_type=authorization_code", APP_ID, SECRET, code);
        String data = HttpKit.get(url);
        return JSONUtil.parse(data);
    }

    /***
     * 获取用户信息
     * @param accessToken accessToken
     * @param openId openId
     * @return 返回信息
     */
    private static JSON getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String data = HttpKit.get(url);
        return JSONUtil.parse(data);
    }

    /***
     * 数据封装
     * @param userInfo 获取的json用户信息
     * @return 返回结果
     */
    private static WeixinUserInfo data(JSON userInfo) {
        WeixinUserInfo weixinUserInfo = new WeixinUserInfo();
        Object openId = userInfo.getByPath("openid");
        Object nickName = userInfo.getByPath("nickname");
        Object sex = userInfo.getByPath("sex");
        Object province = userInfo.getByPath("province");
        Object city = userInfo.getByPath("city");
        Object country = userInfo.getByPath("country");
        Object headImgUrl = userInfo.getByPath("headimgurl");
        ArrayList privilege = userInfo.getByPath("privilege", ArrayList.class);
        Object unionId = userInfo.getByPath("unionid");
        weixinUserInfo
                .setOpenId(openId != null ? openId.toString() : "")
                .setCity(city != null ? city.toString() : "")
                .setNickName(nickName != null ? nickName.toString() : "")
                .setSex(sex != null ? sex.toString() : "")
                .setProvince(province != null ? province.toString() : "")
                .setCountry(country != null ? country.toString() : "")
                .setHeadImgUrl(headImgUrl != null ? headImgUrl.toString() : "")
                .setUnionId(unionId != null ? unionId.toString() : "")
                .setPrivilege(privilege);
        return weixinUserInfo;
    }

}
